package com.stu.jvm.bytebuffer;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.Scanner;

public class ByteBufferTest {

    private static final int size = 1024 * 1024 * 1024;

    public static void main(String[] args) {
        // 开辟一个堆外内存
//        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(size);
//        System.out.println("分配堆外内存！");
        Scanner scanner = new Scanner(System.in);
        scanner.next();
        System.out.println("开始释放内存!");
//        byteBuffer = null;
        System.gc();

        Field declaredFields = Unsafe.class.getDeclaredFields()[0];
        declaredFields.setAccessible(true);
        try {
            Unsafe unsafe = (Unsafe)declaredFields.get(null);
            long allocateMemory = unsafe.allocateMemory(size);
            while(true){
                byte[] bytes = "hello".getBytes();
                for (int i = 0; i < bytes.length; i++) {
                    unsafe.putByte(allocateMemory,bytes[i]);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
